package fun.coding.design.pattern;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class NodeObserver implements Observer{
	private Observable ob;
	private Callback callback;
	private boolean isCallbackExecuted = false;
	
	public NodeObserver(Observable ob) {
		this.ob = ob;
		this.ob.addObserver(this);
	}
	
	/**
	 * This is the public submit function. 
	 * @param node
	 * @param callback
	 */
	public void submit(Object node, Callback callback) {
		((ObservableGraph)ob).addNode(node);
		this.callback = callback;
	}
	
	@Override
	public void update(Observable obs, Object arg) {
		if (obs instanceof ObservableGraph) {
			ObservableGraph og = (ObservableGraph) obs;
			
			List<NodeObserver> nodes = og.getAllDependency(this);
			
			for (NodeObserver n : nodes) {

				if (!this.isCallbackExecuted) {
					this.callback.doSomething();
					this.isCallbackExecuted = true;
				}
			}
		}
	}	
}


